import 'dart:developer';
import 'dart:io';
import '../../common/file_utils.dart';
import '../../index.dart';

class WorkOrderHandlePage extends StatefulWidget {
  late String taskId;
  late String orderId;

  WorkOrderHandlePage({Key? key, required this.taskId, required this.orderId})
      : super(key: key);

  @override
  _WorkOrderHandleState createState() => _WorkOrderHandleState();
}

class _WorkOrderHandleState extends State<WorkOrderHandlePage> {
  List<OrderCfg>? faultReasonList;
  late List<TyPhoto> beforePhotos;
  late List<TyPhoto> afterPhotos;
  late OrderHandleRequest orderHandleRequest;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    beforePhotos = [];
    afterPhotos = [];
    orderHandleRequest = OrderHandleRequest();
    faultReasonList = OrderCfgCache().getOrderCfg(4);
  }

  @override
  Widget build(BuildContext context) {
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          appBar: AppBar(
            title: const Text(
              "处理工单",
            ),
            centerTitle: true,
          ),
          body: _buildBody(), // 构建主页面
        ),
      ),
    );
  }

  Widget _buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      child: ListView(
        children: <Widget>[
          CommonSelect(
            title: "故障原因",
            isRequired: true,
            content: OrderCfgCache.idToString(
                faultReasonList, orderHandleRequest.faultReason),
            onTap: () async {
              List<SelectData>? list =
                  OrderCfgCache.orderCfgListToSelectList(faultReasonList);

              if (list != null) {
                List result =
                    await Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => SelectPage(
                              selectIds: orderHandleRequest.faultReason,
                              listData: list,
                              isRadio: false,
                              title: "请选择故障原因",
                            )));
                setState(() {
                  orderHandleRequest.faultReason = result[0];
                });
                // int index =
                //     max(0, list.indexOf(orderHandleRequest.faultReason ?? ""));
                // PickerUtil.showModalPicker(context,
                //     adapter: PickerDataAdapter<String>(pickerdata: list),
                //     selecteds: [index], onConfirm: (Picker picker, List value) {
                //   setState(() {
                //     orderHandleRequest.faultReason = faultReasonList![picker.selecteds[0]].id;
                //   });
                // });
              } else {
                showToast("暂无数据");
              }
            },
          ),
          CommonPhotoSelect(
            title: "处理前照片",
            photos: beforePhotos,
            isRequired: true,
            max: 12,
            onlyShoot: true,
            isHideDivide: true,
          ),
          CommonMultiLineTextField(
            title: "处理内容",
            isRequired: true,
            isHideDivide: true,
            maxLength: 200,
            content: orderHandleRequest.handleContent,
            onChanged: (value) {
              orderHandleRequest.handleContent = value;
            },
          ),
          CommonPhotoSelect(
            title: "处理后照片",
            photos: afterPhotos,
            max: 12,
            onlyShoot: true,
            isRequired: true,
            isHideDivide: true,
          ),
          Padding(
            padding: const EdgeInsets.only(top: 25, left: 16, right: 16),
            child: ConstrainedBox(
              constraints: const BoxConstraints.expand(height: 55.0),
              child: ElevatedButton(
                onPressed: _formValidation,
                child: Text(
                  "保存",
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      color: Theme.of(context).colorScheme.onBackground),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _formValidation() async {
    if (orderHandleRequest.faultReason == null) {
      showToast("请选择故障原因");
      return;
    }
    if (beforePhotos.isEmpty) {
      showToast("请上传处理前照片");
      return;
    }

    if ((orderHandleRequest.handleContent ?? "").isEmpty) {
      showToast("请填写处理内容");
      return;
    }
    if (afterPhotos.isEmpty) {
      showToast("请上传处理后照片");
      return;
    }

    showLoading(context);
    // 如果有图片就上传图片
    _onUploadBeforePhotos();
  }

  void _onUploadBeforePhotos() async {
    List files = [];
    for (TyPhoto photo in beforePhotos) {
      if (photo.url == null && photo.file != null) {
        File? file = await photo.file!.file;
        if (file != null) {
          files.add(MultipartFileExtended.fromFileSync(
              await FileUtils.compressImage(file),
              filename: file.path.substring(file.path.lastIndexOf("/") + 1)));
        }
      }
    }
    if (files.isNotEmpty) {
      try {
        ResponseData<List<TyFile>> responseData =
            await Api(context).uploadFile(data: {"files": files});
        int i = 0;
        if (responseData.success) {
          String annexUrl = "";
          for (TyPhoto photo in beforePhotos) {
            if (photo.url == null && photo.file != null) {
              photo.url = responseData.dataModel?[i].link;
              i++;
            }
            if (annexUrl.isEmpty) {
              annexUrl = photo.url!;
            } else {
              annexUrl = "$annexUrl,${photo.url}";
            }
          }
          orderHandleRequest.handleBeforImage = annexUrl;
          _onUploadAfterPhotos();
        } else {
          Navigator.of(context).pop();
          showToast("上传图片失败");
        }
      } on DioError catch (e) {
        Navigator.of(context).pop();
        showToast(e.message);
      } on Error catch (e) {
        Navigator.of(context).pop();
        showToast("图片上传失败");
      }
    } else {
      _onUploadAfterPhotos();
    }
  }

  void _onUploadAfterPhotos() async {
    List files = [];
    for (TyPhoto photo in afterPhotos) {
      if (photo.url == null && photo.file != null) {
        File? file = await photo.file!.file;
        if (file != null) {
          files.add(MultipartFileExtended.fromFileSync(
              await FileUtils.compressImage(file),
              filename: file.path.substring(file.path.lastIndexOf("/") + 1)));
        }
      }
    }
    if (files.isNotEmpty) {
      try {
        ResponseData<List<TyFile>> responseData =
            await Api(context).uploadFile(data: {"files": files});
        int i = 0;
        if (responseData.success) {
          String annexUrl = "";
          for (TyPhoto photo in afterPhotos) {
            if (photo.url == null && photo.file != null) {
              photo.url = responseData.dataModel?[i].link;
              i++;
            }
            if (annexUrl.isEmpty) {
              annexUrl = photo.url!;
            } else {
              annexUrl = "$annexUrl,${photo.url}";
            }
          }
          orderHandleRequest.handleAfterImage = annexUrl;
          _onSave();
        } else {
          Navigator.of(context).pop();
          showToast("上传图片失败");
        }
      } on DioError catch (e) {
        Navigator.of(context).pop();
        showToast(e.message);
      } on Error catch (e) {
        Navigator.of(context).pop();
        showToast("图片上传失败");
      }
    } else {
      _onSave();
    }
  }

  void _onSave() async {
    //编辑
    try {
      TaskRequest taskRequest = TaskRequest();
      taskRequest.businessFrom = orderHandleRequest.toJson();
      taskRequest.operationType = "agree";
      taskRequest.taskId = widget.taskId;
      ResponseData responseData =
          await Api(context).handleOrder(taskRequest: taskRequest);
      if (responseData.success) {
        eventBus.fire(OrderEvent(EventType.edit, Order()..id = widget.orderId));
        Navigator.of(context).pop();
        Navigator.popUntil(context, ModalRoute.withName("WorkOrderDetails"));
        await showToast("操作成功");
        //跳转到详情
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            settings: const RouteSettings(name: "WorkOrderDetails"),
            builder: (context) =>
                WorkOrderDetailsPage(orderId: widget.orderId)));
      } else {
        Navigator.of(context).pop();
        showToast(responseData.msg);
      }
    } on Error {
      Navigator.of(context).pop();
      showToast(S.of(context).networkError);
    }
  }
}
